package com.ks.core.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ks.core.request.SmsVariableRequest;
import com.ks.core.request.SmsYuHongRequest;
import com.ks.core.response.SmsVariableResponse;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author kingdee
 */
@Slf4j
public class SmsUtil {

    /**
     * 创蓝api账号
     */
    private static final String account = "N526666651";
//    private static final String account = "CN3130473";
    /**
     * 创蓝api密码
     */
    private static final String password = "aPGoVv12eI3b1d";
//    private static final String password = "RrJ2xId4nDd8e3";

    /**
     * 变量短信url
     */
//    private static final String smsVariableRequestUrl = "http://smssh1.253.com/msg/send/json";
    private static final String smsVariableRequestUrl = "http://smssh1.253.com/msg/variable/json";

    /**
     * 短信url(东方雨虹)测试地址
     */
    private static final String yuHongSmsRequestUrl = "https://esb.yuhong.com.cn/api_repair/SendMessage";



    public static void main(String[] args) {
        sendYuHongSms("13635388534", "测试群发");
    }



    public static boolean sendCountMobile(String mobile,String content){
        StringBuffer sb = new StringBuffer("【建筑e院】");
        sb.append(content);
        return sendYuHongSms(mobile, sb.toString());
    }




    /**
     * 发送短信验证码(东方雨虹)
     *
     * @param mobile 手机号
     * @param code 验证码
     * @param minute 有效时间（分钟）
     * @return
     */
    public static boolean sendCodeForYuHong(String mobile, String code, int minute) {
        StringBuffer sb = new StringBuffer("【建筑e院】");
        sb.append(mobile);
        sb.append("您的验证码为：");
        sb.append(code);
        sb.append(" 请在").append(minute).append("分钟内完成验证，请勿将验证码泄漏给他人。");
        return sendYuHongSms(mobile, sb.toString());
    }

    public static boolean sendUser(String mobile,String content){
        StringBuffer sb = new StringBuffer("【建筑e院】");
        sb.append(content);
        return sendYuHongSms(mobile, sb.toString());
    }

    public static boolean sendClueYuHong(String mobile,String clueId){
        StringBuffer sb = new StringBuffer("【建筑e院】");
        sb.append("修缮平台分配给您的商机已被撤回,商机编号: ");
        sb.append(clueId);
        return sendYuHongSms(mobile, sb.toString());
    }

    public static boolean sendYuHong(String mobile,String clueId){
        StringBuffer sb = new StringBuffer("【建筑e院】");
        sb.append("你有一条线索,线索编号为: ");
        sb.append(clueId);
        sb.append("分配给你");
        return sendYuHongSms(mobile, sb.toString());
    }


    public static boolean sendLwClue(String mobile,String clueId){
        StringBuffer sb = new StringBuffer("【建筑e院】");
        sb.append("完善信息通知！您在雨虹修缮建筑e院提交的找漏屋线索需要继续完善信息。线索编号: ");
        sb.append(clueId);
        return sendYuHongSms(mobile, sb.toString());
    }

    public static boolean sendLk(String mobile,String name){
        StringBuffer sb = new StringBuffer("【建筑e院】");
        sb.append("恭喜您注册成为建筑e院会员，您的推荐人");
        sb.append(name);
        sb.append("提醒您登陆APP升级为链客。链客上报线索操作项目成功享有项目分红，发展下级链客享有推广分红，推荐合作伙伴成功获取5000元现金红包等超级权益。");
        return sendYuHongSms(mobile, sb.toString());
    }



    /**
     * 发送短信(东方雨虹)
     *
     * @param mobile 手机号
     * @param content 内容（东方雨虹的接口会自动在短信内容前添加公司标签【东方雨虹】）
     * @return
     */
    public static boolean sendYuHongSms(String mobile, String content){
        SmsYuHongRequest request = new SmsYuHongRequest(mobile, content);
        String jsonString = JSON.toJSONString(request);
        log.info("请求参数：{}", jsonString);
        String responseStr = SmsUtil.sendYuHongSmsByPost(yuHongSmsRequestUrl, jsonString);
        log.info("响应结果：{}", responseStr);
        JSONObject response = JSON.parseObject(responseStr);
        if ("4".equals(response.getString("out"))) {
            log.info("发送成功");
            return true;
        }
        return false;
    }


    /**
     * 发送短信(东方雨虹)
     *
     * @param path 短信发送的接口地址
     * @param postContent 接口所需参数
     * @return
     */
    public static String sendYuHongSmsByPost(String path, String postContent) {
        URL url;
        try {
            url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 提交模式
            httpURLConnection.setRequestMethod("POST");
            //连接超时 单位毫秒
            httpURLConnection.setConnectTimeout(100000);
            //读取超时 单位毫秒
            httpURLConnection.setReadTimeout(100000);
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            // 设置雨虹短信接口所需的请求头参数
            // 6位随机数
            int randomNum = (int)((Math.random()*9+1)*100000);
            String random = String.valueOf(randomNum);
            // 生成token
            String str = "repair*api*md5";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateNowStr = sdf.format(new Date());
            String token = string2MD5(str+random+dateNowStr);

            httpURLConnection.setRequestProperty("random", random);
            httpURLConnection.setRequestProperty("token", token);

            httpURLConnection.connect();
            OutputStream os = httpURLConnection.getOutputStream();
            os.write(postContent.getBytes("UTF-8"));
            os.flush();

            StringBuilder sb = new StringBuilder();
            int httpRspCode = httpURLConnection.getResponseCode();
            if (httpRspCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * md5加密
     * @param inStr 明文
     * @return 签名值
     */
    public static String string2MD5(String inStr){
        MessageDigest md5 = null;
        try{
            md5 = MessageDigest.getInstance("MD5");
        }catch (Exception e){
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++){
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString().toUpperCase();
    }


    /**
     * 发送短信
     *
     * @param msg
     * @param params
     */
    private static boolean send(String msg, String params) {
        //状态报告
        String report = "true";
        SmsVariableRequest request = new SmsVariableRequest(account, password, msg, params, report);
        String jsonString = JSON.toJSONString(request);
        log.info("请求参数：{}", jsonString);
        String responseStr = SmsUtil.sendSmsByPost(smsVariableRequestUrl, jsonString);
        log.info("响应结果：{}", responseStr);
        SmsVariableResponse response = JSON.parseObject(responseStr, SmsVariableResponse.class);
        if (response.getCode().equals("0")) {
            log.info("发送成功");
            return true;
        }
        return false;
    }


    /**
     * 发送短信
     *
     * @param path
     * @param postContent
     * @return
     */
    public static String sendSmsByPost(String path, String postContent) {
        URL url;
        try {
            url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 提交模式
            httpURLConnection.setRequestMethod("POST");
            //连接超时 单位毫秒
            httpURLConnection.setConnectTimeout(10000);
            //读取超时 单位毫秒
            httpURLConnection.setReadTimeout(10000);
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");

//			PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
//			printWriter.write(postContent);
//			printWriter.flush();

            httpURLConnection.connect();
            OutputStream os = httpURLConnection.getOutputStream();
            os.write(postContent.getBytes("UTF-8"));
            os.flush();

            StringBuilder sb = new StringBuilder();
            int httpRspCode = httpURLConnection.getResponseCode();
            if (httpRspCode == HttpURLConnection.HTTP_OK) {
                // 开始获取数据
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值
     *
     * @return ip
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        System.out.println("x-forwarded-for ip: " + ip);
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            System.out.println("Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            System.out.println("WL-Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
            System.out.println("HTTP_CLIENT_IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
            System.out.println("X-Real-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            System.out.println("getRemoteAddr ip: " + ip);
        }
        return ip;
    }

}
